//
//  WordTipView.swift
//  Keyboard
//
//  Created by zhouzhanglin on 17/8/16.
//  Copyright © 2017年 周张林. All rights reserved.
//

import UIKit

protocol WordTipViewDelgate:class {
    func onSelectedWord(word:String!)->Void
}

/// 单词提示
class WordTipView:UIView
{
    weak var delegate:WordTipViewDelgate?
    
    var scrollView:UIScrollView!
    private var _tipPool:[UIButton] = []
    private var _index:Int = 0
    
    let font = UIFont.systemFont(ofSize: 22)
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        scrollView = UIScrollView(frame: frame)
        scrollView.showsHorizontalScrollIndicator = false
        addSubview(scrollView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func onTap(_ sender:UIButton)->Void{
        delegate?.onSelectedWord(word: (sender.titleLabel?.text)!)
    }
    
    func clear()->Void{
        for btn in _tipPool {
            btn.setTitle("", for: .normal)
        }
        scrollView.contentSize.width = 0
        scrollView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: false)
        _index = 0
    }
    
    func add(word:String!) -> Void {
        if _index < 30
        {
            let btn = getButton(index: _index)
            btn.setTitle(word, for: .normal)
            btn.sizeToFit()
            
            btn.frame.origin.x = scrollView.contentSize.width + 20
            
            scrollView.contentSize.width = btn.frame.origin.x + btn.frame.width
            
            _index = _index + 1
        }
    }
    
    func getButton(index:Int)->UIButton
    {
        if _tipPool.count < index {
            return _tipPool[index]
        }
        
        let btn = UIButton()
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setTitleColor(UIColor(white:0.85,alpha:1)  , for: .highlighted)
        btn.titleLabel?.font = font
        _tipPool.append(btn)
        scrollView.addSubview(btn)
        btn.addTarget( self, action: #selector(onTap(_:)), for: .touchUpInside )
        
        return btn
    }
}
